package com.jsy.file.controller;

import com.jsy.common.constant.StatusCode;
import com.jsy.common.vo.Result;
import com.jsy.fille.util.FastDFSClient;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class FileController {
    /**
     * 上传文件到fastDFS并返回上传文件后可访问地址
     * @param multipartFile 上传文件信息
     * @return 访问url
     */
    @PostMapping
    public Result upload(@RequestParam("file") MultipartFile multipartFile) {

        try {
            byte[] bytes = multipartFile.getBytes();
            String originalFilename = multipartFile.getOriginalFilename();
            String fileExtName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String url = FastDFSClient.upload(bytes, fileExtName);
            return new Result("上传文件成功", url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR, "上传文件失败！");
    }

    @DeleteMapping
    public Result delete(String path) {

        try {
            //  文件路径 path="http://192.168.12.168/group1/M00/00/00/wKgMqF37QvSAX8wtAACH8MULczg18.jpg"
            //替换http://192.168.12.168方便得到组名和远程文件名
            if (!StringUtils.isEmpty(path)){
                String replace = path.replace("http://", "");
                String[] split = replace.split("/");
                String groupName = split[1];

                StringBuilder remoteFileName = new StringBuilder();
                for (int i = 2; i < split.length; i++) {
                    remoteFileName.append(split[i]).append("/");
                }
                remoteFileName.deleteCharAt(remoteFileName.length()-1);
                //删除文件
                FastDFSClient.delete(groupName,remoteFileName.toString());
                return new Result("删除成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR, "删除失败！");
    }

}
